#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command import command
import logging,os
from utility import tools
from settings  import DOWN_FILE_DIR
from utility.file_split import split_file
from utility.memcache_manager import MemcacheManager
import pandas as pd
FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class HospitalDelMonRepListAPI(Resource):
    """
    住院分娩月报
    :request: post
    :param fmsjStart: 分娩时间开始日期
    :param fmsjEnd: 分娩时间结束日期
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)   
            records_ = odoo.env['birth.record'].search_read([],['hospital_id'])  
            data_ = {'dataList': [],'total': 0} 
            is_record_=[]
            if records_:
                for  record_ in records_:
                  if record_['hospital_id'][0] not in is_record_:
                    is_record_.append(record_['hospital_id'][0])   
                    data_['total']+=1
                    query_ = [('hospital_id', '=', record_['hospital_id'][0])]   
                    print (query_)
                    fields = ['id']        
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records] 
                    nan = odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('decc_tezt','=',0),('main_id','in',main_ids)
                        ])
                    nv = odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('decc_tezt','=',1),('main_id','in',main_ids)
                        ]) 
                    weizhi = odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('decc_tezt','=',2),('main_id','in',main_ids) 
                        ]) 
                    query_ = [('decc_fmfs', '=', 0),('hospital_id', '=', record_['hospital_id'][0])]   
                    fields = ['id']        
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]    
                    sc =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])  
                    query_ = [('decc_fmfs', '=', 3),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]  
                    tx =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])
                    query_ = [('decc_fmfs', 'in', [1,2]),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]       
                    twc =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])
                    query_ = [('decc_fmfs', '=', 4),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]     
                    cq =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])
                    query_ = [('decc_fmfs_qt', '=', '医学指征数量'),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]      
                    yxzz =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])  
                    query_ = [('decc_fmfs_qt', '=', '非医学指征数量'),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]        
                    fyxzz =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])                            
                    data_tmp = {
                        'jgName': record_['hospital_id'][-1],
                        'xb': {
                            'male': nan,
                            'female':nv,
                            'unknownGender': weizhi,
                            'total': weizhi+nv+nan
                        },
                        'fmfs': {
                            'sc': sc,
                            'tx': tx,
                            'twc': twc,
                            'cq': cq,
                            'pgc': {
                                'yxzz': yxzz,
                                'fyxzz': fyxzz
                            }
                        }
                    }
                    data_['dataList'].append(data_tmp)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class HospitalDelMonRepExportAPI(Resource):
    """
    导出住院分娩月报
    :request: post
    :param fmsjStart: 分娩时间开始日期
    :param fmsjEnd: 分娩时间结束日期
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            #获取UID
            uid = params.get('uid')
            # 防重校验
            cache = MemcacheManager()
            check = cache.get('hos_del_mon_report'+str(uid))
            if check:
                check = check.split(',')
                data_ ={
                        'blob': str(open(check[0], 'rb').read()),
                        'isOver': 0 #0否 1是
                    }
                if len(check)==1:
                    data_['isOver'] = 1   
                    cache.delete('hos_del_mon_report'+str(uid)) 
                else:    
                    check = check[1:]    
                    cache.set('hos_del_mon_report'+str(uid), ','.join(check))
                return {
                    'code': 0,
                    'data': data_,
                    'msg': 'success',
                } 
            data_ = []
            records_ = odoo.env['birth.record'].search_read([],['hospital_id'])  
            data_ = {'dataList': [],'total': 0} 
            is_record_=[]
            if records_:
                for  record_ in records_:
                  if record_['hospital_id'][0] not in is_record_:
                    is_record_.append(record_['hospital_id'][0])   
                    data_['total']+=1
                    query_ = [('hospital_id', '=', record_['hospital_id'][0])]   
                    print (query_)
                    fields = ['id']        
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records] 
                    nan = odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('decc_tezt','=',0),('main_id','in',main_ids)
                        ])
                    nv = odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('decc_tezt','=',1),('main_id','in',main_ids)
                        ]) 
                    weizhi = odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('decc_tezt','=',2),('main_id','in',main_ids) 
                        ]) 
                    query_ = [('decc_fmfs', '=', 0),('hospital_id', '=', record_['hospital_id'][0])]   
                    fields = ['id']        
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]    
                    sc =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])  
                    query_ = [('decc_fmfs', '=', 3),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]  
                    tx =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])
                    query_ = [('decc_fmfs', 'in', [1,2]),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]       
                    twc =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])
                    query_ = [('decc_fmfs', '=', 4),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]     
                    cq =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])
                    query_ = [('decc_fmfs_qt', '=', '医学指征数量'),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]      
                    yxzz =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])  
                    query_ = [('decc_fmfs_qt', '=', '非医学指征数量'),('hospital_id', '=', record_['hospital_id'][0])] 
                    records = odoo.env['birth.record'].search_read(query_,fields)
                    main_ids = [record['id']  for record in records]        
                    fyxzz =  odoo.env['birth.record.line'].search_count([
                           ('create_date', '>=', params.get('fmsjStart')),
                           ('create_date', '<=', params.get('fmsjEnd')),
                           ('main_id','in',main_ids) 
                        ])                            
                    data_tmp = {
                        '机构名称': record_['hospital_id'][-1],
                        '性别分类-男性数量': nan,
                        '性别分类-女性数量': nv,
                        '性别分类-性别不明': weizhi,
                        '性别分类-合计': weizhi+nv+nan,
                        '分娩方式-顺产数量':sc,
                        '分娩方式-胎吸数量':tx,
                        '分娩方式-臀位产数量':twc,
                        '分娩方式-产钳数量':cq,
                        '分娩方式-医学指征数量':yxzz,
                        '分娩方式-非医学指征数量':fyxzz
                    }
                    data_.append(data_tmp)
            res = {'blob':'','isOver':'1'}
            #print (res)
            if data_:
                col_names=[
                    '机构名称','性别分类-男性数量','性别分类-女性数量','性别分类-合计',
                    '分娩方式-顺产数量','分娩方式-胎吸数量',
                    '分娩方式-臀位产数量','分娩方式-产钳数量','分娩方式-医学指征数量'
                    '分娩方式-非医学指征数量'
                ]
                df=pd.DataFrame(data_)
                file_path='{}{}-{}-0.xlsx'.format(DOWN_FILE_DIR,'住院分娩月报',uid)
                df.to_excel(file_path,columns=col_names,index=False)
                file_path_n = split_file('{}-{}-0.xlsx'.format('住院分娩月报',uid),col_names)
                #初始文件小于3M
                if file_path == file_path_n[0]:
                    res['blob'] = str(open(file_path, 'rb').read())
                    os.remove(file_path)
                else:
                    res['blob'] = str(open(file_path_n[0], 'rb').read()) 
                    os.remove(file_path_n[0])
                    res['isOver'] = '0'
                    #文件大于3M
                    req_flag = ','.join(file_path_n[1:])
                    #文件名保存到缓存里
                    cache.set('hos_del_mon_report'+str(uid), req_flag)
            #print (res)
            return jsonify({'code': 0, 'msg': 'success', 'data': res})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

